import DI from '@/components/MiniBpmn/utils/di';
import { type Option } from '../../../../../types';

class DefaultCcService extends DI {
  value: Array<string | Option> = [];

  constructor(public type: string) {
    super();
  }

  onChange(value: Option[]) {
    this.value = value;
    this.updateProperties(value);
  }

  updateProperties(value: Option[]) {
    const element = this.panel.getElement();
    const moddle = this.root.getModdle();

    const oldExtensionElements = element.businessObject.extensionElements;
    const oldConfig = oldExtensionElements?.values?.filter((it: any) => it.$type !== `flowable:DefaultCc`) || [];

    const values = value.map(it => it.value).join(',');
    const labels = value.map(it => it.value).join(',');

    const extensionElements = moddle.create(
      'bpmn:ExtensionElements',
      {
        values: [
          ...oldConfig,
          moddle.create(
            `flowable:DefaultCc`,
            {
              value: values,
              type: this.type,
              text: labels,
            },
          ),
        ],
      },
    );

    this.root.getModeling().updateProperties(
      element,
      {
        extensionElements
      },
    );
  }

  init() {
    const element = this.panel.getElement();
    const extensionElements = element.businessObject.extensionElements;
    const dom = extensionElements?.values?.find((e: any) => e.$type === `flowable:DefaultCc`);
    const ids: string = dom?.value || '';
    const labels: string = dom?.text || '';
    if (ids) {
      const idArr = ids.split(',');
      const labelArr = labels.split(',');
      this.value = idArr.map((it, index) => ({ value: it, label: labelArr[index] })) as Option[];
    } else {
      this.value = [];
    }
    // console.log('dom', dom, ids, labels, element, this.value);
  }

}

export default DefaultCcService;
